package cn.iocoder.yudao.module.service.service.stepformdata;

import cn.hutool.core.util.ObjUtil;
import cn.iocoder.yudao.framework.tenant.core.util.TenantUtils;
import cn.iocoder.yudao.module.service.service.customer.ServiceCustomerService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

import cn.iocoder.yudao.module.service.controller.admin.stepformdata.vo.*;
import cn.iocoder.yudao.module.service.dal.dataobject.stepformdata.StepFormDataDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.service.dal.mysql.stepformdata.StepFormDataMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.service.enums.ErrorCodeConstants.*;

/**
 * 表单 Service 实现类
 *
 * @author 数创万维
 */
@Service
@Validated
public class StepFormDataServiceImpl implements StepFormDataService {

    @Resource
    private StepFormDataMapper stepFormDataMapper;

    @Resource
    private ServiceCustomerService serviceCustomerService;

    @Override
    public Long createStepFormData(StepFormDataSaveReqVO createReqVO) {
        // 插入
        StepFormDataDO stepFormData = BeanUtils.toBean(createReqVO, StepFormDataDO.class);
        stepFormDataMapper.insert(stepFormData);
        // 返回
        return stepFormData.getId();
    }

    @Override
    public void updateStepFormData(StepFormDataSaveReqVO updateReqVO) {
        // 更新
        StepFormDataDO updateObj = BeanUtils.toBean(updateReqVO, StepFormDataDO.class);
        stepFormDataMapper.updateById(updateObj);
    }

    @Override
    public void deleteStepFormData(Long id) {
        // 删除
        stepFormDataMapper.deleteById(id);
    }


    @Override
    public StepFormDataDO getStepFormData(Long id) {
        return stepFormDataMapper.selectById(id);
    }

    @Override
    public PageResult<StepFormDataDO> getStepFormDataPage(StepFormDataPageReqVO pageReqVO) {
        return stepFormDataMapper.selectPage(pageReqVO);
    }

    @Override
    public void createStepFormData(Long tenantId, Long fromUserId, Long formId, String formContent) {
        if (ObjUtil.isNull(formId) || ObjUtil.isNull(fromUserId) || ObjUtil.isNull(tenantId)) {
            return;
        }
        TenantUtils.execute(tenantId, () -> {
            StepFormDataDO dataDO = new StepFormDataDO();
            dataDO.setFormId(formId)
                    .setCustomerId(fromUserId)
                    .setFormContent(formContent);
            stepFormDataMapper.insert(dataDO);

            serviceCustomerService.updateCustomerFormByLoginUserId(fromUserId);

        });
    }
}